# !/usr/bin/env python
# -*-coding:utf-8 -*-
"""
# File       : user_view.py
# Time       ：2023/7/9 16:28
# Author     ：Y-aong
# version    ：python 3.7
# Description：
    用户视图
    user views
"""
from flask import request
from flask_restx import fields

from apis.system_oauth import system_oauth_ns
from apis.system_oauth.models import SystemUser, SystemUserRoleRelation, SystemUserGroupRelation
from apis.system_oauth.schema.user_schema import SystemUserSchema
from public.api_utils.api_decorator import handle_api_error
from public.base_model import db
from public.base_response import MarshalModel
from public.base_view import BaseView, BaseDetailsView

user = {
    'username': fields.String(description='用户名称'),
    'email': fields.String(description='用户邮箱'),
    'phone': fields.String(description='用户电话'),
    'password': fields.String(description='用户密码'),
    'img_url': fields.String(description='用户图片链接'),
    'group_owner': fields.Boolean(description='是否为群组所有者'),
    'dept_id': fields.Integer(description='部门ID'),
}

user_marshal = MarshalModel('user', system_oauth_ns)


class UserDetailView(BaseDetailsView):
    url = '/user/detail'

    def __init__(self, *args, **kwargs):
        super(UserDetailView, self).__init__(*args, **kwargs)
        self.table_orm = SystemUser
        self.table_schema = SystemUserSchema

    @handle_api_error()
    @system_oauth_ns.doc(description="获取用户详情")
    @system_oauth_ns.expect(user_marshal.detail_request())
    @system_oauth_ns.marshal_with(user_marshal.detail_response(user))
    def get(self):
        """获取用户详情"""
        return super(UserDetailView, self).get()


class UserView(BaseView):
    url = '/user'

    def __init__(self, *args, **kwargs):
        super(UserView, self).__init__(*args, **kwargs)
        self.table_orm = SystemUser
        self.table_schema = SystemUserSchema
        self.is_logger = True
        username = self.form_data.get('username') or ''
        self.post_action = f'创建用户{username}'
        self.put_action = '修改用户'
        self.delete_action = f'删除用户ID为{self.table_id}'

    def handle_response_data(self):
        role_ids = self.form_data.get('role_ids')
        group_ids = self.form_data.get('group_ids')
        if request.method in ['POST', 'PUT']:
            if role_ids:
                for role_id in role_ids:
                    obj = SystemUserRoleRelation(user_id=self.table_id, role_id=role_id)
                    db.session.add(obj)
                    db.session.commit()
            if group_ids:
                for group_id in group_ids:
                    obj = SystemUserGroupRelation(user_id=self.table_id, group_id=group_id)
                    db.session.add(obj)
                    db.session.commit()

        elif request.method == 'DELETE':
            db.session.query(SystemUserRoleRelation).filter(
                SystemUserRoleRelation.user_id == self.table_id).update({'active': 0})

            db.session.query(SystemUserGroupRelation).filter(
                SystemUserRoleRelation.user_id == self.table_id).update({'active': 0})
            db.session.commit()

    @handle_api_error()
    @system_oauth_ns.doc(description='获取用户列表')
    @system_oauth_ns.expect(user_marshal.list_request(user))
    @system_oauth_ns.marshal_with(user_marshal.list_response(user))
    def get(self):
        """获取用户列表"""
        return super(UserView, self).get()

    @handle_api_error()
    @system_oauth_ns.doc(description='创建用户')
    @system_oauth_ns.expect(user_marshal.create_request(user))
    @system_oauth_ns.marshal_with(user_marshal.create_response())
    def post(self):
        """创建用户"""
        return super(UserView, self).post()

    @handle_api_error()
    @system_oauth_ns.doc(description='修改用户')
    @system_oauth_ns.expect(user_marshal.update_request(user))
    @system_oauth_ns.marshal_with(user_marshal.update_response())
    def put(self):
        """修改用户"""
        return super(UserView, self).put()

    @handle_api_error()
    @system_oauth_ns.doc(description='删除用户')
    @system_oauth_ns.expect(user_marshal.delete_request())
    @system_oauth_ns.marshal_with(user_marshal.delete_response())
    def delete(self):
        """删除用户"""
        return super(UserView, self).delete()
